package com.authentication;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class MyLDAP {
	///for ldap 
    private String ldapServerName;
    private String rootdn;
    private String rootpass;
    private String rootContext;
    private String organizationDN;
    private String userdn;
    private String loginAttribute;
	public void loadConfig(){
		/*
		Properties prop = new Properties();
		 
    	try {
               //load a properties file
    		prop.load(new FileInputStream("ldapconfig.properties"));
 
               //get the property value and print it out
            ldapServerName = prop.getProperty("ldapServerName");
    		rootdn = prop.getProperty("rootdn");
    		rootpass = prop.getProperty("rootpass");
    		rootContext = prop.getProperty("rootContext");
    		organizationDN = prop.getProperty("organizationDN");
    		loginAttribute = prop.getProperty("loginAttribute");
    	} catch (IOException ex) {
    		ex.printStackTrace();
        }
    */
		this.ldapServerName = "localhost";
		this.rootdn = "cn=admin,dc=lvtn,dc=com";
		this.rootpass = "admin";
		this.rootContext="dc=lvtn,dc=com";
		this.organizationDN = "ou=people,dc=lvtn,dc=com";
		this.loginAttribute ="uid";
	
	}
	
	public String getCredential(String username, String password){
		//load Config from property file
		this.loadConfig();
		
		Properties env = new Properties();
        
        env.put( Context.INITIAL_CONTEXT_FACTORY,
                 "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put( Context.PROVIDER_URL, "ldap://" + this.ldapServerName + "/" + this.rootContext );
        userdn = this.loginAttribute + "=" + username + "," + this.organizationDN;
        env.put( Context.SECURITY_PRINCIPAL, userdn );
        env.put( Context.SECURITY_CREDENTIALS,password);
        
        try {
                // obtain initial directory context using the environment
                DirContext ctx = new InitialDirContext( env );
               System.out.println(ctx.getNameInNamespace());
                
                SearchControls searchCtls = new SearchControls();
        		
    			//Specify the attributes to return
    			String returnedAtts[]={"uid","x-authenticationKey"};
    			searchCtls.setReturningAttributes(returnedAtts);
    		
    			//Specify the search scope
    			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
     
    			//specify the LDAP search filter
    			
    			String searchFilter = "(&(objectClass=x-account)(" + this.loginAttribute + "=" + username + "))";
     
    			//initialize counter to total the results
    			int totalResults = 0;
     
     
    			// Search for objects using the filter
    			NamingEnumeration answer = ctx.search("", searchFilter, searchCtls);
     
    			//Loop through the search results
    			while (answer.hasMoreElements()) {
    		    		SearchResult sr = (SearchResult)answer.next();
     
    				totalResults++;
    				
    			//	System.out.println(">>>" + sr.getName());
     
    				
    				Attributes attrs = sr.getAttributes();
    				if (attrs != null) {
    					try {
    					//System.out.println("   username: " + attrs.get("uid").get());
    					//System.out.println("   x-AuthenticationKey: " + attrs.get("x-authenticationKey").get());
    					 return "" + attrs.get("x-authenticationKey").get();
    					} 
    					catch (NullPointerException e)	{
    					System.out.println("Errors listing attributes: " + e);
    					}
    				}
     
    			}
     
     			//System.out.println("Total results: " + totalResults);
    			ctx.close();
                /*
                System.out.println(ctx.lookup("uid=tuan,ou=people"));
                ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");
                System.out.println(ctx.lookup("uid=tuan,ou=people"));
                ctx.close();
                */
        } catch (NamingException e) {
    	    e.printStackTrace();
    	}
        return null;
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			MyLDAP l = new MyLDAP();
			System.out.println(l.getCredential("tuan", "123456"));
			
	}

}
